package com.submit.demo.config;

import com.submit.demo.component.JwtAuthenticationTokenFilter;
import com.submit.demo.component.RestAuthenticationEntryPoint;
import com.submit.demo.component.RestfulAccessDeniedHandler;
import com.submit.demo.model.Admin;
import com.submit.demo.model.Collector;
import com.submit.demo.model.Submitter;
import com.submit.demo.repository.AdminRepository;
import com.submit.demo.repository.CollectorRepository;
import com.submit.demo.repository.SubmitterRepository;
import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Slf4j
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private CollectorRepository collectorRepository;
    @Autowired
    private SubmitterRepository submitterRepository;

    @Autowired
    private final AuthIgnoreConfig authIgnoreConfig;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] urls = authIgnoreConfig.getIgnoreUrls().stream().distinct().toArray(String[]::new);
        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(urls)
                .permitAll()
                .antMatchers("/login/checkLogin", "/sms/code", "/login/logout")
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                .anyRequest()
                .authenticated();
        http.headers().frameOptions().sameOrigin();
        http.headers().cacheControl();
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return username -> {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            String code = (String) session.getAttribute("code");
            log.info("从session_id: {} \n 获取到验证码:{}", session.getId(), code);
            request.removeAttribute("code");
            Admin admin;
            Collector collector;
            Submitter submitter;
            if(code == null) code = "";
            if((admin = adminRepository.findAdminByUsername(username)) != null)
                return new User(username, passwordEncoder().encode(admin.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
            if((collector = collectorRepository.findCollectorByPhone(username)) != null)
                return new User(username, code, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_COLLECTOR"));
            if((submitter = submitterRepository.findSubmitterByPhone(username)) != null)
                return new User(username, code, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_SUBMITTER"));
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
